#include "fxcc/core/graph/opengl3/ImGuiGlfwApp.h"

using namespace fxcc::imgui::graph::opengl3;

void GlfwApp::OnDestroy() {

    ImNodes::DestroyContext();
  
    ImGui_ImplOpenGL3_Shutdown();
    ImGui_ImplGlfw_Shutdown();
    ImGui::DestroyContext();

    fxcc::graph::opengl3::GlfwApp::OnDestroy();
};

void GlfwApp::OnEdit() {

};

int GlfwApp::Run()
{
    if (!Init())
    {
        ztclog::info("failed init app");
        return 1;
    }
    while (!glfwWindowShouldClose(m_GlfwWindow))
    {
        glfwPollEvents();

        OnUpdate();

        // Start the Dear ImGui frame
        ImGui_ImplOpenGL3_NewFrame();
        ImGui_ImplGlfw_NewFrame();
        ImGui::NewFrame();
        OnEdit();

        // Rendering
        ImGui::Render();
        
        m_Input.Clear();

        OnFrameRender();

        ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());

        ImGuiIO &io = ImGui::GetIO();
        if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
        {
            GLFWwindow *backup_current_context = glfwGetCurrentContext();
            ImGui::UpdatePlatformWindows();
            ImGui::RenderPlatformWindowsDefault();
            glfwMakeContextCurrent(backup_current_context);
        }

        glfwSwapBuffers(m_GlfwWindow);
    }

    OnDestroy();
    return 0;
}

bool GlfwApp::Init()
{
    if (!fxcc::graph::opengl3::GlfwApp::Init())
    {
        return false;
    }
    if (!InitImGui())
    {
        ztclog::info("failed init imgui");
        return false;
    }
    return true;
};

bool fxcc::imgui::graph::opengl3::GlfwApp::InitImGui()
{
    // Setup Dear ImGui context
    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO &io = ImGui::GetIO();
    (void)io;
    io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
    io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;  // Enable Gamepad Controls
    io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;     // Enable Docking
    // io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;   // Enable Multi-Viewport / Platform Windows
    // io.ConfigViewportsNoAutoMerge = true;
    // io.ConfigViewportsNoTaskBarIcon = true;

    // Setup Dear ImGui style
    // ImGui::StyleColorsDark();
    // ImGui::StyleColorsLight();
    ImGui::StyleColorsClassic();

    // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
    ImGuiStyle &style = ImGui::GetStyle();
    if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
    {
        style.WindowRounding = 0.0f;
        style.Colors[ImGuiCol_WindowBg].w = 1.0f;
    }

    // Setup Platform/Renderer backends
    ImGui_ImplGlfw_InitForOpenGL(m_GlfwWindow, true);
    ImGui_ImplOpenGL3_Init("#version 130");

    ImNodes::CreateContext();

    return true;
}
